package com.weijun.keepalive_daemon.process

import com.weijun.keepalive_daemon.DaemonKeepAlive
import com.weijun.keepalive_daemon.logE
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException

/**
 * @author: weijun
 * date: 2023/7/6
 * description:
 */
class Daemon(private val daemonConfigs:DaemonConfigs) {

    private var mBufferedReader : BufferedReader ?= null

    fun initDaemon() {
        val context = DaemonKeepAlive.application ?: return
        val processName = getProcessName() ?: return
        val packageName = context.packageName

        if (processName.startsWith(daemonConfigs.PERSISTENT_CONFIG.processName)) {
            "Daemon initDaemon onPersistentCreate".logE()
            ProcessHelper.mDaemonStrategy?.onPersistentCreate(context, daemonConfigs)
        } else if (processName.startsWith(daemonConfigs.DAEMON_ASSISTANT_CONFIG.processName)) {
            "Daemon initDaemon onDaemonAssistantCreate".logE()
            ProcessHelper.mDaemonStrategy?.onDaemonAssistantCreate(context, daemonConfigs)
        } else if (processName.startsWith(packageName)) {
            "Daemon initDaemon init".logE()
            ProcessHelper.mDaemonStrategy?.init(context)
        }
        releaseIO()
    }

    private fun getProcessName(): String? {
        return try {
            mBufferedReader = BufferedReader(FileReader(File("/proc/self/cmdline")))
            mBufferedReader?.readLine()?.trim { it <= ' ' }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun releaseIO() {
        try {
            mBufferedReader?.close()
            mBufferedReader = null
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

}